package me.leiusual.sharing.ui.store.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.StoreCategories

/**
 * author: leiusual
 * create on: 2019-07-26
 * description:
 */
class StoreCategoryAdapter(
    private val listener: StoreCategoryViewHolder.Listener
) : RecyclerView.Adapter<StoreCategoryViewHolder>() {

  private val dataSet = mutableListOf<StoreCategories.Response.Category.Item>()

  private var selectedPosition = -1

  override fun getItemCount(): Int {
    return dataSet.size
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StoreCategoryViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val itemView = inflater.inflate(R.layout.view_holder_store_category, parent, false)
    return StoreCategoryViewHolder(itemView, object : StoreCategoryViewHolder.Listener {
      override fun onCategoryClicked(category: StoreCategories.Response.Category.Item) {
        selectedPosition = dataSet.indexOf(category)
        notifyDataSetChanged()
        listener.onCategoryClicked(category)
      }
    })
  }

  override fun onBindViewHolder(holder: StoreCategoryViewHolder, position: Int) {
    holder.bind(dataSet[position], selectedPosition == position)
  }

  fun submitList(list: List<StoreCategories.Response.Category.Item>) {
    dataSet.clear()
    dataSet.addAll(list)
    selectedPosition = -1
    notifyDataSetChanged()
  }
}